package cs2340.droidceptiontodo;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

public class Files {
	/**
	 * This method determines if the user exists
	 * and if it does, if the password is correct for a login attempt
	 * 
	 * @param cxt, Context of application required for openFileInput
	 * @param login, The username that will be checked
	 * @param password, The password that will be checked
	 * @return int,
	 * 		-3 or -2 if there is an error
	 * 		-1 if the user does not exist
	 * 		0 if the password is wrong
	 * 		1 if the user is logged in
	 */
	private static String currentUser="";
	private static Context aContext= null;
	public static int verifyUser(Context cxt, String login, String password){
		String fileName = login+ ".txt"; 
		FileInputStream fis =null;
		String passwordFound = null;
		try
		{
			//openFileInput() method is from Context class library (method of android)
			//If file not found in the default emulator directory, it will throw FileNotFounfException
			//way to check manually--> DDMS, save it locally and open, cannot access from within emulator
			//It is caught in catch block
			fis = cxt.openFileInput(fileName); 
			DataInputStream in = new DataInputStream(fis);
			//Read one line from the file
			//personName, email, username, password
			String readOutput = in.readLine();
			Log.d("DEBUG","Line read: "+ readOutput);
			//Split the line into individual fields
			String[] tempString = readOutput.split(":");
			//The last index in array, index=3, in the line is password. 
			//trim() is used to remove white space in the string
			passwordFound = tempString[3].trim();
			Log.d("DEBUG","Password in file: "+ passwordFound);
			//Either password was empty/not found or password is different from what was entered now
	        if ((passwordFound == null)||(passwordFound.length() ==0)||(!(passwordFound.equals(password))))
			{
				return 0;
			}
			else{
				//Password found in the file is matching with the password entered now
				if(passwordFound.equals(password)){
					currentUser = login;
					aContext = cxt;
					return 1;
				}
			}
			if (fis != null)
				fis.close(); //close the fileinputstream 
		}
		    //This exception happens when you login with file with login name was not found.
		    //It should be the case of new user
		catch(FileNotFoundException ex)
		{
			return -1;
		}
		catch(IOException e)
		{
			return -2;
		} //returns a specific logMessage as output
		catch(Exception e){
			return -2;
		}
		return -3;
	}
	/**
	 * Creates a new user by writing the user to a text file
	 * Also creates ToDo file for the user which keeps track of the user's
	 * saved ToDoItems
	 * 
	 * @param cxt, The context of the application, required for openFileOutput
	 * @param login, The new username
	 * @param password, The desired password
	 * @param email The user's email address
	 * @param name The user's name
	 */
	public static void createUser(Context cxt, String login, String password, String email, String name){
		FileOutputStream fos = null; 
		FileOutputStream fosToDo = null;
		//File name will be same as login
		String  fileName = login +".txt";
		//ToDo file name for the user
		String  fileNameToDo = login +"ToDo.txt";
		//Prepare the following string to write in the user file
		String writeString = name+":"+email+":"+login+":"+password;
		Log.d("DEBUG","filename"+fileName);
		Log.d("DEBUG","writeString"+writeString);
		try
		{
			//Create a new file with login name
			fos = cxt.openFileOutput(fileName, Context.MODE_PRIVATE); //to make it unaccessible
			PrintStream  writer = new PrintStream(fos); //to write each line
			//Write all the information  in the user file
			writer.println(writeString); //writeString is the whole string written to the file
			//Create ToDo file for the user
			fosToDo = cxt.openFileOutput(fileNameToDo, Context.MODE_PRIVATE); //to make it unaccessible			
			fos.close();
			fosToDo.close();
		}
		catch(Exception e)
		{
			Log.d("DEBUG", e.getLocalizedMessage());
		}
	}
	
	/**
	 * This method inserts the ToDoItem object into the corresponding ToDo file
	 * @param toDoItem an instance of TODOItem class
	 */
	public static void insertToDoItem(ToDoItem toDoItem){
		FileOutputStream fosToDo = null;
		String  fileNameToDo = currentUser +"ToDo.txt";
		try{
			//Open the user file in APPEND mode
			fosToDo = aContext.openFileOutput(fileNameToDo, aContext.MODE_APPEND); 
			//fosToDo = cxt.openFileOutput(fileNameToDo, cxt.MODE_PRIVATE);
			Log.d("DEBUG", "FileToDo opened for writing: "+fileNameToDo);
			PrintStream  writer = new PrintStream(fosToDo); //to write each line
			//Write the todo item in the user file
			writer.println(toDoItem.toString()); 
		    fosToDo.close();
		}
		catch(Exception e)
		{
			Log.d("DEBUG", e.getLocalizedMessage());
		}		
	}
	
	/**
	 * This method reads all ToDoItems from the user's items file and returns a list of ToDoItems.
	 * If there are no ToDoItems saved, it will return a List with one ToDoItem with the name 
	 * "No ToDoItems found"
	 * 
	 * @return List of the ToDoItems
	 */
	public static List<ToDoItem> getStoredItems()
	{
		Category.addCategory("Personal");
		Category.addCategory("School");
		Category.addCategory("Work");
		List<ToDoItem> items = new ArrayList<ToDoItem>();
		FileInputStream fis =null;
		String  fileNameToDo = currentUser +"ToDo.txt";
		String[] itemComponents = null;
		String[] itemCompFinal = null;
		try
		{
			//Open the user's ToDofile 
			fis = aContext.openFileInput(fileNameToDo); 
			//Check if any ToDoItem is stored in the file earlier
			if (fis.available()>0)
			{
				Log.d("DEBUG", "ToDo File opened for reading: " +fileNameToDo);
				DataInputStream in = new DataInputStream(fis);				 
				String readOutput = null;
				while((readOutput = in.readLine()) != null)
				{
					itemComponents = readOutput.split(":");
					
					// Change "null" to ""
					itemCompFinal = new String[itemComponents.length];
					for(int i=0; i<itemComponents.length; i++) {
						itemCompFinal[i] = itemComponents[i].equals("null")? "" : itemComponents[i];
					}
							
	//				items.add(new ToDoItem(itemCompFinal));
				}
			}
			// Not sure if this is necessary, is it taken care of in the text file?
			/*
			else {
				String[] noItemsFound = new String[6];
				noItemsFound[0] = "No ToDoItemsFound";
				items.add(new ToDoItem(noItemsFound));
			}*/
		}
		catch(Exception e){
			Log.d("DEBUG", e.getLocalizedMessage());
		}
		
		return items;		
	}
	
	public static void logoutUser() {
		currentUser = "";
	}
}